package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;

/**
 * 创建日期: 2022-01-20-11-06
 * author : WQW
 * description: 用户登录相关服务实现
 */
@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    /**
     * @description 用户登录
     * @author WQW
     * @date 2022/1/20 11:08
     * @param
     * @param request
     * @return com.mall.user.dto.UserLoginResponse
     */
    @Override
    @Transactional
    public UserLoginResponse login(UserLoginRequest request) {
        UserLoginResponse loginResponse = new UserLoginResponse();
        try {
            // 1.参数校验
            request.requestCheck();
            // 2.验证用户名以及密码
            Member member = validateUsernameAndPwd(request);
            // 3.判断该用户是否已经激活
            // validateUserActivate(request);
            // 4.产生一个合法的JWT
            String token = getToken(member);
            // 5.封装返回对象
            loginResponse = userConverterMapper.converter(member);
            loginResponse.setToken(token);
            loginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            loginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            log.info("LoginServiceImpl.login request :" + JSON.toJSONString(request.getUserName()));
        }catch (Exception e){
            log.error("LoginServiceImpl.login occur Exception :"+ e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionProcessorUtils.wrapperHandlerException(loginResponse,e);
        }
        return loginResponse;
    }


    /**
     * @description 获取一个合法的token
     * @author WQW
     * @date 2022/1/20 14:14
     * @param
     * @param member
     * @return java.lang.String
     */
    private String getToken(Member member) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", member.getId());
        map.put("username", member.getUsername());
        map.put("file", member.getFile());
        return JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build().creatJwtToken();
    }

    /**
     * @description 验证用户是否已经激活
     * @author WQW
     * @date 2022/1/20 14:15
     * @param
     * @param request
     * @return void
     */
    private void validateUserActivate(UserLoginRequest request) {
        Example example1 = new Example(UserVerify.class);
        example1.createCriteria().andEqualTo("username", request.getUserName());
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example1);
        if (CollectionUtils.isEmpty(userVerifies)) {
            throw new ValidateException(
                    SysRetCodeConstants.DATA_NOT_EXIST.getCode(),
                    SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        }
        UserVerify userVerify = userVerifies.get(0);
        // 如果用户尚未激活，则抛出用户未激活异常
        if ("N".equals(userVerify.getIsVerify())) {
            throw new ValidateException(
                    SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode(),
                    SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
        }
    }

    /**
     * @description 验证账户密码是否匹配
     * @author WQW
     * @date 2022/1/20 14:11
     * @param
     * @param request
     * @return com.mall.user.dal.entitys.Member
     */
    private Member validateUsernameAndPwd(UserLoginRequest request) {
        Example example = new Example(Member.class);
        //example.createCriteria().andEqualTo("username", request.getUserName());
        example.createCriteria().andEqualTo("email", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)) {
            throw new ValidateException(
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode(),
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }
        Member member = members.get(0);
        if (!DigestUtils.md5DigestAsHex(request.getPassword().getBytes()).equals(member.getPassword())) {

            throw new ValidateException(
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode(),
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }
        return member;
    }
}
